package com.tianxiao.faas.biz.service.corner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianxiao.faas.common.util.PageUtils;
import com.tianxiao.faas.mapper.dao.UserLogModelMapper;
import com.tianxiao.faas.mapper.model.UserLogModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserLogService {
    final static Logger logger = LoggerFactory.getLogger(UserLogService.class);
    @Resource
    private UserLogModelMapper userLogModelMapper;

    public void log(Long userId, String action, Object args) {
        try {
            UserLogModel record = new UserLogModel();
            record.setAction(action);
            long actionTime = System.currentTimeMillis();
            record.setActionTime(actionTime);
            if (args instanceof Serializable) {
                record.setContent(JSON.toJSONString(args));
            }
            record.setDeleted(0);
            record.setUserId(userId);
            userLogModelMapper.insertSelective(record);
        } catch (Exception e) {
            List<Object> arg = new ArrayList<>(3);
            arg.add(userId);
            arg.add(action);
            arg.add(args);
            logger.error("log error, param:{}", JSONObject.toJSONString(arg));
        }
    }

    public List<UserLogModel> page(String action, Long userId, Integer page, Integer pageSize) {
        return userLogModelMapper.page(userId, action, PageUtils.getOffset(page, pageSize), pageSize);
    }

    public Integer count(String action, Long userId) {
        return userLogModelMapper.count(userId, action);
    }
}
